<?php
namespace Admin\Controller;
use Think\Controller;
class MenuController extends Controller {
	
	//自定义菜单首页
    public function index(){
        //从数据库获取数据
        $data = M('menu')->select();
        $data = $this->tree($data);

        //发送数据并显示
        $this->assign('data',$data);
        $this->display();
    }

    //添加自定义菜单
    public function add(){
        if(IS_POST){
            //接收数据
            $data = I('post.');
            $model = M('menu');
            //验证菜单数量
            if($data['pid'] == 0){
                $count = $model->where('pid=0')->count();
                if($count >= 3){
                    $this->error('一级菜单最多三个');
                }
                //验证菜单长度
                if(strlen($data['name']) > 12){
                    $this->error('一级菜单最多四个中文');
                }
            }else{
                $count = $model->where("pid={$data['pid']}")->count();
                if($count >= 5){
                    $this->error('二级菜单最多五个');
                }
                //验证菜单长度
                if(strlen($data['name']) > 21){
                    $this->error('一级菜单最多七个中文');
                }
            }
            //插入数据库
            $res = $model->add($data);
            if($res){
                $this->success('添加成功',U('Menu/index'));
            }else{
                $this->error('添加失败');
            }
        }else{
            $this->display();
        }
    }

    //修改自定义菜单
    public function edit(){
        if(IS_POST){
            //接收数据
            $data = I('post.');
            $model = M('menu');
            //验证菜单长度
            if($data['pid'] == 0 && strlen($data['name']) > 12){
                $this->error('一级菜单最多四个中文');
            }elseif(strlen($data['name']) > 21){
                $this->error('一级菜单最多七个中文');
            }
            //插入数据库
            $res = $model->save($data);
            if($res){
                $this->success('修改成功',U('Menu/index'));
            }else{
                $this->error('修改失败');
            }
        }else{
            //获取数据
            $model = M('menu');
            $data = $model->find(I('id'));
            $menu = $model->field('id,name')->where('pid=0')->select();

            $this->assign('menu',$menu);
            $this->assign('data',$data);
            $this->display();
        }
    }

    //删除自定义菜单
    public function del(){
        $res = M('menu')->delete(I('id'));
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    //更新自定义菜单
    public function update(){
        //获取菜单的json数据
        $menu = $this->menuJson();
        //1.获取access_token
        $base = M('base')->find();
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$base['appid'].'&secret='.$base['appsecret'];
        $json = $this->myCurl($url);
        $access_token = json_decode($json,true)['access_token'];

        //创建自定义菜单
        //设置url
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
        //发送请求，处理结果
        $res = $this->myCurl($url,$menu);
        $errmsg = json_decode($res,true)['errmsg'];
        if($errmsg == 'ok'){
            $this->success('创建菜单成功');
        }else{
            if(empty($errmsg)){
                $this->error('错误是'.$res);
            }else{
                $this->error('错误信息是'.$errmsg);
            }
        }
    }

    /**数组转换方法
     * @param array $data 要转换的数组
     * @param int $pid 一级菜单的id
     * @return array
     */
    private function tree($data,$pid=0){
        $arr = array();
        //数组转换
        foreach($data as $k1 => $v1){
            //查找一级菜单
            if($v1['pid'] == $pid){
                $arr[] = $v1;
                //在一级菜单下继续查找二级菜单
                foreach($data as $k2 => $v2){
                    if($v2['pid'] == $v1['id']){
                        $v2['name'] = '--'.$v2['name'];
                        $arr[] = $v2;
                    }
                }
            }
        }
        return $arr;
    }

    /**
     * 生成自定义菜单要的json
     * @param void
     * @return json 反正自定义菜单的json
     */
    private function menuJson(){
        $data = M('menu')->select();

        //转成需要的数据
        $menu = array();
        $i = 0;
        foreach($data as $k => $v){
            if($v['pid'] == 0){
                $menu['button'][$i] = $v;
                foreach($data as $k1 => $v1){
                    if($v['id'] == $v1['pid']){
                        $menu['button'][$i]['sub_button'][] = $v1;
                    }
                }
                $i++;
            }
        }

        //删除多余字段,转换数据
        foreach($menu['button'] as $k => &$v){
            if($v['type'] == 1){
                $v['type'] = 'click';
            }else{
                $v['type'] = 'view';
            }
            unset($v['id']);
            unset($v['pid']);
            if(empty($v['key'])){
                unset($v['key']);
            }else{
                unset($v['url']);
            }
            if($v['sub_button']){
                unset($v['type']);
                if(empty($v['key'])){
                    unset($v['url']);
                }else{
                    unset($v['key']);
                }
                foreach($v['sub_button'] as $k1 => &$v1){
                    if($v1['type'] == 1){
                        $v1['type'] = 'click';
                    }else{
                        $v1['type'] = 'view';
                    }
                    unset($v1['id']);
                    unset($v1['pid']);
                    if(empty($v1['key'])){
                        unset($v1['key']);
                    }else{
                        unset($v1['url']);
                    }
                }
            }
        }
        return json_encode($menu,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

    /**
     * curl请求，如果没有传$data就为get请求
     * @param string $url 请求的路径
     * @param mixed $data 传递参数，可以为字符串或者数组
     * @return string 请求成功时返回成功的字符串，失败时返回错误信息
     */
    private function myCurl($url,$data=''){
        //1.创建句柄
        $ch = curl_init();
        //2.设置参数,设置URL时，要用绝对路径
        curl_setopt($ch,CURLOPT_URL,$url); //设置URL
        //如果没有设置不输出，那么默认会将获取到的网页直接输出
        //设置捕获但是不输出，如果该函数没有设置，那么默认输出，并且执行完返回一个true
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

        //判断是否有$data的值
        //模拟POST传输数据
        if($data){
            curl_setopt($ch,CURLOPT_POST,1);
            //发送数据,Content-Type头将会被设置成multipart/form-data
            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        }
        //设置不验证证书
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);

        //3.执行
        $res = curl_exec($ch);
        if(curl_error($ch)){
            return curl_error($ch);
        }else{
            return $res;
        }
        //4.关闭
        curl_close($ch);
    }
}